<template>
  <div class="dictionary-management">
    <div class="page-container">
      <div class="page-header">
        <h2>数据字典管理</h2>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增字典项
        </el-button>
      </div>
      
      <div class="dictionary-content">
        <!-- 左侧分类树 -->
        <div class="category-tree">
          <el-card>
            <template #header>
              <div class="tree-header">
                <span>字典分类</span>
                <el-button type="text" @click="handleAddCategory">
                  <el-icon><Plus /></el-icon>
                </el-button>
              </div>
            </template>
            <el-tree
              :data="categoryTree"
              :props="treeProps"
              node-key="id"
              :default-expand-all="true"
              :current-node-key="currentCategoryId"
              @node-click="handleCategoryClick"
            >
              <template #default="{ node, data }">
                <div class="tree-node">
                  <span>{{ node.label }}</span>
                  <div class="node-actions">
                    <el-button type="text" size="small" @click.stop="handleEditCategory(data)">
                      <el-icon><Edit /></el-icon>
                    </el-button>
                    <el-button type="text" size="small" @click.stop="handleDeleteCategory(data)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>
                </div>
              </template>
            </el-tree>
          </el-card>
        </div>
        
        <!-- 右侧字典项列表 -->
        <div class="dictionary-list">
          <el-card>
            <template #header>
              <div class="list-header">
                <span>{{ currentCategoryName }} - 字典项</span>
                <div class="header-actions">
                  <el-input
                    v-model="searchKeyword"
                    placeholder="搜索字典项"
                    style="width: 200px; margin-right: 10px"
                    @keyup.enter="handleSearch"
                  >
                    <template #append>
                      <el-button @click="handleSearch">
                        <el-icon><Search /></el-icon>
                      </el-button>
                    </template>
                  </el-input>
                  <el-button type="primary" @click="handleAdd">
                    <el-icon><Plus /></el-icon>
                    新增
                  </el-button>
                </div>
              </div>
            </template>
            
            <el-table
              v-loading="loading"
              :data="tableData"
              stripe
              border
            >
              <el-table-column prop="code" label="代码" width="120" />
              <el-table-column prop="name" label="名称" width="200" />
              <el-table-column prop="value" label="值" width="150" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="sort" label="排序" width="80" align="center" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
                    {{ row.status === 'active' ? '启用' : '禁用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="160" />
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="handleEdit(row)">
                    编辑
                  </el-button>
                  <el-button 
                    :type="row.status === 'active' ? 'warning' : 'success'"
                    size="small"
                    @click="handleToggleStatus(row)"
                  >
                    {{ row.status === 'active' ? '禁用' : '启用' }}
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDelete(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="pagination.page"
                v-model:page-size="pagination.size"
                :total="pagination.total"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </div>
      </div>
    </div>
    
    <!-- 字典项表单对话框 -->
    <DictionaryFormDialog
      v-model="formDialogVisible"
      :form-data="formData"
      :category-id="currentCategoryId"
      :is-edit="isEdit"
      @success="handleFormSuccess"
    />
    
    <!-- 分类表单对话框 -->
    <CategoryFormDialog
      v-model="categoryDialogVisible"
      :form-data="categoryFormData"
      :is-edit="isCategoryEdit"
      @success="handleCategorySuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DictionaryFormDialog from './components/DictionaryFormDialog.vue'
import CategoryFormDialog from './components/CategoryFormDialog.vue'

interface DictionaryItem {
  id: number
  code: string
  name: string
  value: string
  description: string
  sort: number
  status: 'active' | 'inactive'
  createTime: string
}

interface CategoryNode {
  id: string
  label: string
  children?: CategoryNode[]
}

const loading = ref(false)
const tableData = ref<DictionaryItem[]>([])
const currentCategoryId = ref('')
const searchKeyword = ref('')
const formDialogVisible = ref(false)
const categoryDialogVisible = ref(false)
const formData = ref<Partial<DictionaryItem>>({})
const categoryFormData = ref<Partial<CategoryNode>>({})
const isEdit = ref(false)
const isCategoryEdit = ref(false)

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const treeProps = {
  children: 'children',
  label: 'label'
}

// 分类树数据
const categoryTree = ref<CategoryNode[]>([
  {
    id: 'work_type',
    label: '作业类型',
    children: [
      { id: 'work_type_1', label: '高空作业' },
      { id: 'work_type_2', label: '动火作业' },
      { id: 'work_type_3', label: '电气作业' }
    ]
  },
  {
    id: 'risk_level',
    label: '风险等级',
    children: [
      { id: 'risk_level_1', label: '一级（高风险）' },
      { id: 'risk_level_2', label: '二级（中风险）' },
      { id: 'risk_level_3', label: '三级（低风险）' }
    ]
  },
  {
    id: 'safety_measures',
    label: '安全措施库',
    children: [
      { id: 'safety_measures_1', label: '个人防护' },
      { id: 'safety_measures_2', label: '环境控制' },
      { id: 'safety_measures_3', label: '管理措施' }
    ]
  },
  {
    id: 'personnel_type',
    label: '人员类型',
    children: [
      { id: 'personnel_type_1', label: '特种作业人员' },
      { id: 'personnel_type_2', label: '气测人员' },
      { id: 'personnel_type_3', label: '安全员' }
    ]
  }
])

// 当前分类名称
const currentCategoryName = computed(() => {
  if (!currentCategoryId.value) return '请选择分类'
  
  const findCategory = (nodes: CategoryNode[], id: string): string => {
    for (const node of nodes) {
      if (node.id === id) return node.label
      if (node.children) {
        const found = findCategory(node.children, id)
        if (found) return found
      }
    }
    return ''
  }
  
  return findCategory(categoryTree.value, currentCategoryId.value) || '未知分类'
})

// 模拟字典数据
const mockDictionaryData: Record<string, DictionaryItem[]> = {
  work_type_1: [
    {
      id: 1,
      code: 'HIGH_ALTITUDE',
      name: '高空作业',
      value: 'high_altitude',
      description: '在2米以上高度进行的作业',
      sort: 1,
      status: 'active',
      createTime: '2025-01-01 10:00:00'
    }
  ],
  work_type_2: [
    {
      id: 2,
      code: 'HOT_WORK',
      name: '动火作业',
      value: 'hot_work',
      description: '使用明火或产生火花的作业',
      sort: 2,
      status: 'active',
      createTime: '2025-01-01 10:00:00'
    }
  ],
  risk_level_1: [
    {
      id: 3,
      code: 'LEVEL_1',
      name: '一级（高风险）',
      value: 'level_1',
      description: '高风险作业，需要严格管控',
      sort: 1,
      status: 'active',
      createTime: '2025-01-01 10:00:00'
    }
  ]
}

// 获取字典列表
const fetchDictionaryList = async () => {
  if (!currentCategoryId.value) {
    tableData.value = []
    pagination.total = 0
    return
  }
  
  try {
    loading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    let data = mockDictionaryData[currentCategoryId.value] || []
    
    // 搜索过滤
    if (searchKeyword.value) {
      data = data.filter(item => 
        item.name.includes(searchKeyword.value) ||
        item.code.includes(searchKeyword.value) ||
        item.description.includes(searchKeyword.value)
      )
    }
    
    // 分页
    const start = (pagination.page - 1) * pagination.size
    const end = start + pagination.size
    
    tableData.value = data.slice(start, end)
    pagination.total = data.length
  } catch (error: any) {
    ElMessage.error(error.message || '获取字典列表失败')
  } finally {
    loading.value = false
  }
}

// 处理分类点击
const handleCategoryClick = (data: CategoryNode) => {
  currentCategoryId.value = data.id
  pagination.page = 1
  fetchDictionaryList()
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchDictionaryList()
}

// 新增字典项
const handleAdd = () => {
  if (!currentCategoryId.value) {
    ElMessage.warning('请先选择分类')
    return
  }
  
  formData.value = {}
  isEdit.value = false
  formDialogVisible.value = true
}

// 编辑字典项
const handleEdit = (row: DictionaryItem) => {
  formData.value = { ...row }
  isEdit.value = true
  formDialogVisible.value = true
}

// 删除字典项
const handleDelete = async (row: DictionaryItem) => {
  try {
    await ElMessageBox.confirm(`确定要删除字典项 "${row.name}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('删除成功')
    fetchDictionaryList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 切换状态
const handleToggleStatus = async (row: DictionaryItem) => {
  try {
    const action = row.status === 'active' ? '禁用' : '启用'
    await ElMessageBox.confirm(`确定要${action}字典项 "${row.name}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(`${action}成功`)
    fetchDictionaryList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '操作失败')
    }
  }
}

// 新增分类
const handleAddCategory = () => {
  categoryFormData.value = {}
  isCategoryEdit.value = false
  categoryDialogVisible.value = true
}

// 编辑分类
const handleEditCategory = (data: CategoryNode) => {
  categoryFormData.value = { ...data }
  isCategoryEdit.value = true
  categoryDialogVisible.value = true
}

// 删除分类
const handleDeleteCategory = async (data: CategoryNode) => {
  try {
    await ElMessageBox.confirm(`确定要删除分类 "${data.label}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('删除成功')
    // 这里应该重新加载分类树
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 表单提交成功
const handleFormSuccess = () => {
  formDialogVisible.value = false
  fetchDictionaryList()
}

// 分类表单提交成功
const handleCategorySuccess = () => {
  categoryDialogVisible.value = false
  // 这里应该重新加载分类树
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  fetchDictionaryList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchDictionaryList()
}

onMounted(() => {
  // 默认选择第一个分类
  if (categoryTree.value.length > 0) {
    currentCategoryId.value = categoryTree.value[0].id
    fetchDictionaryList()
  }
})
</script>

<style lang="scss" scoped>
.dictionary-management {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #333;
    }
  }
  
  .dictionary-content {
    display: flex;
    gap: 20px;
    height: calc(100vh - 200px);
    
    .category-tree {
      width: 300px;
      flex-shrink: 0;
      
      .tree-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .tree-node {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        
        .node-actions {
          display: none;
          
          .el-button {
            padding: 4px;
          }
        }
        
        &:hover .node-actions {
          display: block;
        }
      }
    }
    
    .dictionary-list {
      flex: 1;
      
      .list-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .header-actions {
          display: flex;
          align-items: center;
        }
      }
      
      .pagination-container {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
      }
    }
  }
}
</style>

